<script setup lang="ts">
import { useAppStore, useControllerStore } from '@/store';
import HomeRequest from '@/request/homeRequest';
import useToast from '@/hooks/useToast';
import { navigate } from '@/utils/navigate';

interface IState {
  show: boolean;
  data?: IProductInformation;
  selectSkuKey: { [comboId: number]: Set<number> };
  nums: number;
}

const store = useAppStore();
const controllerStore = useControllerStore();
const state = reactive<IState>({ show: false, selectSkuKey: {}, nums: 1 });
const { showToast } = useToast();

watch(
  () => controllerStore.$state.skuPackageSelectionPopup,
  (skuPackageSelectionPopup) => {
    if (skuPackageSelectionPopup && controllerStore.$state.productInformation) {
      state.data = controllerStore.$state.productInformation;
      fetchObtainProductDetails(state.data.goodsId);
    } else {
      state.show = false;
      state.selectSkuKey = {};
      state.nums = 1;
      state.data = undefined;
    }
  },
);

// 获得产品规格
const fetchObtainProductDetails = (id: number) => {
  HomeRequest.ObtainProductDetails({ id, hasLoading: true }).then((res) => {
    state.data = { ...state.data, ...res.data };
    state.show = true;
  });
};

// 规格选项事件
const handleSkuSelect = (comboId: number, relationId: number) => {
  const currentSelection = new Set(state.selectSkuKey[comboId] || []);

  // 切换选中状态
  if (currentSelection.has(relationId)) {
    currentSelection.delete(relationId);
  } else {
    const maxSelectable = state.data!.goodsCombos.find((combo) => combo.goodsComboId === comboId)?.chooseNums || 0;
    if (currentSelection.size < maxSelectable) {
      currentSelection.add(relationId);
    } else {
      showToast(`只能选择${maxSelectable}项，请先点击取消原先选择的`);
    }
  }

  state.selectSkuKey = {
    ...state.selectSkuKey,
    [comboId]: currentSelection,
  };
};

// 加入购物车
const handleAddToShoppingCart = () => {
  const precondition = handlePrecondition();
  if (!precondition) return;
  if (store.$state.shoppingCart.find((item) => item.goodsType === 15)) {
    showToast('补差价产品不能和其他产品一起购买');
    return;
  }
  store.updateShoppingCartSku({ type: 'add', data: { ...state.data!, sku: precondition.sku, variantIds: precondition.variantIds, nums: state.nums } });
  controllerStore.$patch({ skuPackageSelectionPopup: false, productInformation: undefined });
  showToast('加入购物车成功');
};

// 直接下单
const handleDirectOrderPlacement = () => {
  const precondition = handlePrecondition();
  if (!precondition) return;
  const products = { ...state.data!, sku: precondition.sku, variantIds: precondition.variantIds, nums: state.nums };
  controllerStore.$patch({ skuPackageSelectionPopup: false, productInformation: undefined });
  navigate({ url: `/subcontract/home/submitOrder/index?products=${encodeURIComponent(JSON.stringify(products))}` });
};

// 下单或者加入购物车的前置条件
const handlePrecondition = () => {
  // 存储未满足要求的组合信息
  const unselectedCombos: any[] = [];

  const selectedData = state.data!.goodsCombos.map((combo) => {
    const selectedIds = state.selectSkuKey[combo.goodsComboId] || new Set();
    const selectedItemsData = combo.list.filter((item) => selectedIds.has(item.relationId));
    if (selectedItemsData.length < combo.chooseNums) {
      unselectedCombos.push({ comboName: combo.comboName, requiredSelection: combo.chooseNums });
    }
    return selectedItemsData;
  });
  if (unselectedCombos.length > 0) {
    const message = unselectedCombos.map((combo) => `${combo.comboName} 必须要选择 ${combo.requiredSelection} 项`).join('\n');
    showToast(`${message}`);
    return;
  }
  let sku = '';
  const variantIds: string[] = [];
  selectedData.forEach((item, index) => {
    if (index !== 0) sku += '|||';
    item.forEach((itemData, _index) => {
      if (_index !== 0) sku += '___';
      sku += itemData.relationGoodsName;
      variantIds.push(itemData.relationVariantId);
      if (itemData.relationVariantSku !== '无') {
        sku += '/' + itemData.relationVariantSku;
      }
    });
  });
  return { sku, variantIds: variantIds.toString() };
};
</script>

<template>
  <van-popup :show="state.show" @close="() => controllerStore.$patch({ skuPackageSelectionPopup: false, productInformation: undefined })">
    <view class="c-br c-pd w-screen flex justify-center" v-if="state.data">
      <view class="c-br bg-white c-pd w-full overflow-scroll max-h-500px">
        <view class="flex">
          <view class="w-80px h-80px c-br overflow-hidden">
            <image class="w-full h-full" :src="state.data.mainImage" lazy-load mode="aspectFill" />
          </view>
          <view class="pl-8px box-border overflow-hidden flex-1 flex flex-col justify-between">
            <view class="flex items-start">
              <view class="flex-1 c-text-ellipsis-2 w-full fw-bold">
                {{ state.data.name }}
              </view>
              <view v-if="state.data.visitFlag !== 0" class="ml-4px c-text-8 px-4px py-2px rounded-4px border-1px border-#999999 border-solid c-text-color-grey">服务上门</view>
            </view>
            <view v-if="state.data.introduce" class="w-fit mt-4px max-w-96% c-text-ellipsis rounded-4px text-#ec820d bg-#fdf7e3 px-4px py-1px c-text-10 block">
              {{ state.data.introduce }}
            </view>
            <view v-if="state.data.remark" class="w-fit mt-4px max-w-96% c-text-ellipsis rounded-4px text-white bg-#36af06d7 px-4px py-1px c-text-10 block">
              {{ state.data.remark }}
            </view>
          </view>
        </view>
        <view class="w-full mb-8px" v-for="item in state.data.goodsCombos" :key="item.goodsComboId">
          <view class="c-text-14 my-8px fw-bold">{{ item.comboName }} (必选{{ item.chooseNums }}项)</view>
          <view class="grid grid-cols-3 gap-2">
            <template v-for="_item in item.list" :key="_item.relationId">
              <view
                class="text-align-center c-text-12 c-br border-1px border-solid py-4px border-#c5c1c1"
                :class="
                  state.selectSkuKey[item.goodsComboId]?.has(_item.relationId)
                    ? 'bg-#FFFBF0 text-#ED8A2A border-#E0B83E'
                    : state.selectSkuKey[item.goodsComboId]?.size === item.chooseNums && !state.selectSkuKey[item.goodsComboId]?.has(_item.relationId) && 'border-#F1F1F1 text-#a8a7a7'
                "
                @click="handleSkuSelect(item.goodsComboId, _item.relationId)"
              >
                {{ _item.relationGoodsName }}
                {{ _item.relationVariantSku !== '无' ? `/${_item.relationVariantSku}` : '' }}
              </view>
            </template>
          </view>
        </view>
        <RenderProductDiscount :data="state.data" :count="state.nums - 1" :hasSku="true" />
        <view class="flex justify-between my-8px">
          <RenderProductPrice :data="state.data" :count="state.nums - 1" :hasSku="true" />
          <view class="flex items-center">
            <i class="i-gg:remove c-color c-text-16" @click="state.nums > 1 && state.nums--" />
            <text class="mx-8px fw-bold c-text-14">{{ state.nums }}</text>
            <i class="i-icon-park-solid:add-one c-color c-text-16" @click="() => (state.nums += 1)" />
          </view>
        </view>
        <view class="flex justify-center">
          <view class="flex-1 c-bg-sec text-white py-8px text-align-center rounded-tl-8px rounded-bl-8px" @click="handleAddToShoppingCart">加入购物车</view>
          <view class="flex-1 c-bg py-8px text-align-center rounded-tr-8px rounded-br-8px" @click="handleDirectOrderPlacement">立即下单</view>
        </view>
      </view>
    </view>
  </van-popup>
</template>
